package com.local.videoplayer.ads;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.support.v4.app.FragmentActivity;
import com.jaaksi.superclean.dialogs.AppRateDialog;
import com.jaaksi.superclean.utils.ToastUtil;
import com.jaaksi.superclean.utils.Utils;

public class AppRater {

    private final static int RUNNING_COUNT_FOR_RATING = 4;

    public static void promptUserToRate(Activity context) {
        // Rating
        if (isReadyToShow(context)) {
            showRate(context);
        }
    }

    private static boolean isReadyToShow(Context context) {
        SharedPreferences prefs = context.getSharedPreferences("rate", 0);
        if (prefs.getBoolean("showed", false)) {
            // User either rated app, or doesn't want to
            return false;
        }

        // Check time of last request
        long running_count = prefs.getLong("open_count", 0);
        // This is the first call. Save the time of this request.
        SharedPreferences.Editor editor = prefs.edit();
        editor.putLong("open_count", ++running_count);
        editor.commit();
        if (running_count >= RUNNING_COUNT_FOR_RATING) {
            return true;
        }

        return false;
    }

    public static void showRate(final Context mContext) {
        SharedPreferences prefs = mContext.getSharedPreferences("rate", 0);
        final SharedPreferences.Editor editor = prefs.edit();
        AppRateDialog dialog = new AppRateDialog();
        dialog.setRateListener(new AppRateDialog.RateListener() {
            @Override
            public void onRate() {
                if (editor != null) {
                    editor.putBoolean("showed", true);
                    editor.commit();
                }
                Uri uri =
                        Uri.parse(String.format("market://details?id=%s", mContext.getPackageName()));
                if (Utils.isIntentSafe((Activity) mContext, uri)) {
                    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    intent.setPackage("com.android.vending");
                    mContext.startActivity(intent);
                } else {
                    ToastUtil.showLong(mContext, "Can't find google play store!");

                }
            }

            @Override
            public void onCancel() {
                if (editor != null) {
                    editor.putBoolean("showed", true);
                    editor.commit();
                }
            }
        });
        dialog.showDialog(((FragmentActivity) mContext).getSupportFragmentManager());
    }
}